/*布局
 * @Author: kevin.huang 
 * @Date: 2018-07-21 12:20:01 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-04-09 21:59:20
 * Copyright (c): kevin.huang Released under MIT License
  * var defaultOpts = {
        onExpanded:null ,// function (pr) {//展开，收缩 pr=max/min},
        onLoaded:null,//加载完成
        items: []  //参考items说明
  };
  items:[ {
      width: 230,
      title: '系统面板', //标题
      iconCls: 'myaccount', //样式
      dataType:'html',//html iframe json
      content:	内容或者url
  	},{
        header:false, //是否需要标题栏
        width: 'auto', //宽度
        title: 'tab模块',
        content: 内容或者url,
        dataType:'html',//html iframe json
        toolbar:工具栏配置json
    }
  ]
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['$B', 'panel'], function (_$B) {
            return factory(global, _$B);
        });
    } else {
        if(!global["$B"]){
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    var Layout = function (jqObj, opts) {
        $B.extend(this, Layout); //继承父类
        this.jqObj = jqObj.addClass("k_box_size k_layout_main");
        this.opts = opts;
        this.panels = [];
        var _this = this;
        var panelOpt = {
            title: '', //标题
            iconCls: null, //图标cls，对应icon.css里的class
            toolbar: null, //工具栏对象
            width: 'auto',
            height: '100%',
            shadow: false, //是否需要阴影
            radius: false, //是否圆角
            header: true, //是否显示头部
            content: null, //静态内容或者url地址
            dataType: 'html', //当为url请求时，html/json/iframe
            closeable: false, //是否关闭
            expandable: false, //可左右收缩
            onLoaded: null, //function () { },//加载后
            onExpanded: null // function (pr) { },//左右收缩后
        };
        var widtdSet = this.anylisLayoutSize();
        var onCreated = function () {
            if (this.data("i") > 0) {
                this.css("border-left", "none");
            }
            if(typeof _this.opts.onCreated === "function"){
                _this.opts.onCreated.call(this,{i:this.data("i"),title:this.data("title")});
            }
        };
        var onExpanded = function () {
            _this.resize();
        };
        var loadFn = this.opts.onLoaded;
        var onLoaded = function(data){
            if(typeof loadFn === "function"){
                var $p = this.parent();
                loadFn.call(this,data,{i:$p.data("i"),title:$p.data("title")});
            }
        };
        for (var i = 0, len = this.opts.items.length; i < len; ++i) {
            var _popts = $.extend({}, panelOpt, this.opts.items[i]);
            var $it = $("<div class='k_layout_item k_box_size'></div>").appendTo(this.jqObj).data("width", _popts.width);
            _popts.width = widtdSet[i];
            _popts.draggable = false;
            $it.data("i", i);
            $it.data("title",_popts.title);
            _popts.onCreated = onCreated;
            _popts.onExpanded = onExpanded;
            _popts.onLoaded = onLoaded;
            var panel = new $B.Panel($it, _popts);
            this.panels.push(panel);
        }
        var nsId = $B.getUUID();
        $(window).on("resize."+nsId,$B.delayFun(function () {
            if( _this.resize){
                _this.resize();
            }else{
                $(this).off("."+nsId);
            }            
        }, 10));
    };
    Layout.prototype = {
        constructor: Layout,
        anylisLayoutSize: function () {
            var tmp = {},
                _this = this,
                allWidth = 0,
                autoCount = 0;
            for (var i = 0, len = this.opts.items.length; i < len; ++i) {
                var w = this.opts.items[i].width;
                var isNum = !(typeof w === 'string' || !w);
                tmp[i] = isNum ? parseInt(w) : 'auto';
                if (isNum) {
                    allWidth = allWidth + tmp[i];
                } else {
                    autoCount++;
                }
            }
            if (autoCount > 0) {
                var avgWidth = (_this.jqObj.width() - allWidth) / autoCount;
                for (var k in tmp) {
                    if (tmp[k] === 'auto') {
                        tmp[k] = avgWidth;
                    }
                }
            }
            return tmp;
        },
        resize: function () {
            var allWidth = this.jqObj.width(),
                acfwidth = 0;
            var autoIts = [];
            this.jqObj.children(".k_layout_item").each(function () {
                var $t = $(this);
                if ($t.data("width") === 'auto') {
                    autoIts.push($t);
                }
                acfwidth = acfwidth + $t.outerWidth();
            });
            var len = autoIts.length;
            var diffw = allWidth - acfwidth;
            var avgW = diffw / len;
            for (var i = 0, l = autoIts.length; i < l; ++i) {
                var w = autoIts[i].width();
                autoIts[i].width(w + avgW);
            }
        },
        /**
         * args:{title:'标题',iconCls:'图标样式'}/args=title,
         * panelIdx:模板索引
         ***/
        setTitle: function (args, panelIdx) {
            this.panels[panelIdx].setTitle(args);
        },
        /**
         *panelIdx:面板的索引、对应items里面的数据下标,
         args={
            url: null,//url地址
            dataType:'html/json/iframe',
            title:'设置该项会改变标题，可是不设置',
            iconCls:'设置新的图标，可是不设置'
         }
         * panelIdx:模板索引
         **/
        load: function (args, panelIdx) {
            if (args.title || args.iconCls) {
                this.setTitle(args, panelIdx);
            }
            this.panels[panelIdx].load(args);
        },
        /**更新内容
         *content：内容
         * panelIdx :模板索引
         * ****/
        updateContent: function (content, panelIdx) {
            var $p = this.panels[panelIdx];
            $p.updateContent(content);
        },
        /**获取iframe
         * panelIdx :模板索引
         * ****/
        getIfr: function (panelIdx) {
            return this.panels[panelIdx].getIfr();
        },
        /**
         * 获取当前的url
         * **/
        getUrl: function (panelIdx) {
            return this.panels[panelIdx].opts.url;
        },
        /**销毁***/
        destroy: function () {
            for (var i = 0, len = this.panels.length; i < len; ++i) {
                this.panels[i].destroy();
            }
            this["super"].destroy.call(this);
            this.panels = null;
        }
    };
    $B["Layout"] = Layout;
    return Layout;
}));